package com.ext.aic.handler;

import android.content.Context;
import android.text.Layout;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.ext.aic.R;
import com.ext.aic.components.AIContinueWriteBottomPopup;
import com.ext.aic.components.ObservableRTEditText;
import com.ext.aic.databinding.EditBubbleViewBinding;
import com.ext.aic.events.OnWriteBackContinueContentListener;
import com.ext.aic.utils.XPopupUtils;
import com.eyinfo.android_pure_utils.ObjectManager;
import com.eyinfo.android_pure_utils.utils.PixelUtils;

import lombok.Getter;

public class BubblePositionHandler {

    private PopupWindow popupWindow;
    private EditBubbleViewBinding binding;
    private AIContinueWriteBottomPopup bottomPopup;
    private int screenWidth;
    private int screenHeight;
    @Getter
    private OnWriteBackContinueContentListener writeBackContinueContentListener;

    // 修改方法参数为PopupWindow类型
    public void showBubbleAtCursor(ObservableRTEditText editText) {
        screenWidth = ObjectManager.getScreenWidth(editText.getContext());
        screenHeight = ObjectManager.getScreenHeight(editText.getContext());
        editText.post(() -> {
            try {
                int[] location = calculateCursorPosition(editText);
                adjustPopupPosition(editText.getContext(), location[0], location[1]);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void hideBubble() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    private int[] calculateCursorPosition(ObservableRTEditText editText) {
        int selectionStart = editText.getSelectionStart();
        Layout layout = editText.getLayout();

        // 获取光标所在行底部坐标
        int line = layout.getLineForOffset(selectionStart);
        float x = layout.getPrimaryHorizontal(selectionStart);
        float y = layout.getLineBottom(line);

        // 转换为屏幕绝对坐标
        int[] editTextLocation = new int[2];
        editText.getLocationOnScreen(editTextLocation);
        return new int[]{
                (int) (editTextLocation[0] + x),
                (int) (editTextLocation[1] + y)
        };
    }

    private void adjustPopupPosition(Context context, int x, int y) {
        View contentView = popupWindow.getContentView();
        contentView.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        );
        int padding = PixelUtils.dip2px(context, 10);
        int maxWidth = screenWidth - PixelUtils.dip2px(context, 24);
        int maxHeight = screenHeight - PixelUtils.dip2px(context, 180);
        if (y > maxHeight) {
            contentView.setPadding(0, 0, 0, padding);
            if (x < 100) {
                contentView.setBackgroundResource(R.drawable.bubble_arrow_down_left);
            } else if ((maxWidth - x) < 100) {
                contentView.setBackgroundResource(R.drawable.bubble_arrow_down_right);
            } else {
                contentView.setBackgroundResource(R.drawable.bubble_arrow_down_center);
            }
            y -= PixelUtils.dip2px(context, 86);
        } else {
            contentView.setPadding(0, padding, 0, 0);
            if (x < 100) {
                contentView.setBackgroundResource(R.drawable.bubble_arrow_up_left);
            } else if ((maxWidth - x) < 100) {
                contentView.setBackgroundResource(R.drawable.bubble_arrow_up_right);
            } else {
                contentView.setBackgroundResource(R.drawable.bubble_arrow_up_center);
            }
            y += PixelUtils.dip2px(context, 16);
        }
        x -= PixelUtils.dip2px(context, 50);
        // 边界检查
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics metrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(metrics);
        int bubbleWidth = contentView.getMeasuredWidth();
        // 右侧越界处理
        if (x + bubbleWidth > metrics.widthPixels) {
            x = metrics.widthPixels - bubbleWidth - PixelUtils.dip2px(context, 16);
        }
        if (popupWindow.isShowing()) {
            popupWindow.update(x, y, -1, -1);
        } else {
            popupWindow.showAtLocation(contentView,
                    Gravity.TOP | Gravity.START,
                    x,
                    y
            );
        }
    }

    private void bindAIWriteBubble(Context context) {
        View popupView = View.inflate(context, R.layout.edit_bubble_view, null);
        binding = EditBubbleViewBinding.bind(popupView);
        RelativeLayout root = binding.getRoot();
        root.setOnClickListener(this::onAiContinueWriteClick);
        popupWindow = new PopupWindow(
                root,
                PixelUtils.dip2px(context, 110),
                PixelUtils.dip2px(context, 52),
                false);
        popupWindow.setElevation(16f);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(false);
    }

    public void onAiContinueWriteClick(View view) {
        Context context = view.getContext();
        if (bottomPopup != null && bottomPopup.isShow()) {
            return;
        }
        hideBubble();
        bottomPopup = new AIContinueWriteBottomPopup(context);
        writeBackContinueContentListener = bottomPopup;
        XPopupUtils.getInstance().showBottomDialog(context, bottomPopup, 0x00ff0000);
    }

    private void setupSelectionListener(ObservableRTEditText editText) {
        editText.addOnSelectionChangeListener((start, end) -> {
            if (start == end) {
                showBubbleAtCursor(editText);
            } else {
                popupWindow.dismiss();
            }
        });
    }

    public void initBubble(Context context, ObservableRTEditText editText) {
        bindAIWriteBubble(context);
        setupSelectionListener(editText);
    }
}
